//
//  AppDelegate.m
//  ZYZB
//
//  Created by ENERGY on 2018/6/11.
//  Copyright © 2018年 ENERGY. All rights reserved.
//

#import "AppDelegate.h"
#import "MainViewController.h"

#import "WXApi.h"
#import "UserGuideViewController.h"
// 引入JPush功能所需头文件
#import "JPUSHService.h"
// iOS10注册APNs所需头文件
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif
// 如果需要使用idfa功能所需要引入的头文件（可选）
#import <AdSupport/AdSupport.h>
@interface AppDelegate ()<JPUSHRegisterDelegate>

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
    [WXApi registerApp:@"wx9f6afefa7cac8198"];
    
    //实例化
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    //背景颜色
    self.window.backgroundColor = [UIColor whiteColor];
//    //主视图
//    MainViewController *mainVc = [[MainViewController alloc] init];
//    [self.window setRootViewController:mainVc];
//    [self.window makeKeyAndVisible];
    
    //设置app属性
    [self setupAppStyle];
    
    //Required
    //notice: 3.0.0及以后版本注册可以这样写，也可以继续用之前的注册方式
    JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
    entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound;
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        // 可以添加自定义categories
        // NSSet<UNNotificationCategory *> *categories for iOS10 or later
        // NSSet<UIUserNotificationCategory *> *categories for iOS8 and iOS9
    }
    [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
    
    // Optional
    // 获取IDFA
    // 如需使用IDFA功能请添加此代码并在初始化方法的advertisingIdentifier参数中填写对应值
    NSString *advertisingId = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
    
    // Required
    // init Push
    // notice: 2.1.5版本的SDK新增的注册方法，改成可上报IDFA，如果没有使用IDFA直接传nil
    // 如需继续使用pushConfig.plist文件声明appKey等配置内容，请依旧使用[JPUSHService setupWithOption:launchOptions]方式初始化。
    [JPUSHService setupWithOption:launchOptions appKey:@"ba77188a1e340ec557452fad"
                          channel:@"App Store"
                 apsForProduction:0
            advertisingIdentifier:advertisingId];
    
    
    
    //判断是不是第一次启动应用
    if(![[NSUserDefaults standardUserDefaults] boolForKey:@"firstLaunch"])
    {
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"firstLaunch"];
        NSLog(@"第一次启动");
        //如果是第一次启动的话,使用UserGuideViewController (用户引导页面) 作为根视图
        UserGuideViewController *userGuideViewController = [[UserGuideViewController alloc] init];
        self.window.rootViewController = userGuideViewController;
    }
    else
    {
        NSLog(@"不是第一次启动");
        //如果不是第一次启动的话,使用LoginViewController作为根视图
        MainViewController *mainVc = [[MainViewController alloc] init];
        [self.window setRootViewController:mainVc];
        
        
    }
    [self.window makeKeyAndVisible];
    
    
    return YES;
}

//设置app属性
- (void)setupAppStyle{
    //修改状态栏颜色 + plist文件
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
//    //设置nav title颜色
//    NSDictionary *attributes=[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor],NSForegroundColorAttributeName,nil];
//    [UINavigationBar appearance].titleTextAttributes = attributes;
//    //设置nav背景颜色
////    [UINavigationBar appearance].barTintColor = getColor(mainColor);
//    [UINavigationBar appearance].barTintColor = getColor(mainColor);
    //设置tab title颜色
    [UITabBar appearance].tintColor = getColor(mainColor);
//    [UINavigationBar appearance].tintColor = [UIColor whiteColor];
    
    //设置背景颜色
    [UITabBar appearance].barTintColor = [UIColor whiteColor];
    // 去掉TabBar上边的线
//    [[UITabBar appearance] setTranslucent:NO];
//    [[UITabBar appearance] setShadowImage:[[UIImage alloc] init]];
//    [[UITabBar appearance] setBackgroundImage:[[UIImage alloc] init]];
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    [application setApplicationIconBadgeNumber:0];
    [application cancelAllLocalNotifications];
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    [application setApplicationIconBadgeNumber:0];
    [application cancelAllLocalNotifications];
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    /// Required - 注册 DeviceToken
    [JPUSHService registerDeviceToken:deviceToken];
}

#pragma mark- JPUSHRegisterDelegate
// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
    [JPUSHService setBadge:0];
    // Required
    NSDictionary * userInfo = notification.request.content.userInfo;
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
    }
    completionHandler(UNNotificationPresentationOptionAlert); // 需要执行这个方法，选择是否提醒用户，有Badge、Sound、Alert三种类型可以选择设置
}

// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
    [JPUSHService setBadge:0];
    
//    HomeOneViewController *ctl = [[HomeOneViewController alloc] init];
//    MainViewController *tabBar = (MainViewController *)self.window.rootViewController;//获取window的跟视图,并进行强制转换
//    if ([tabBar isKindOfClass:[UITabBarController class]]) {//判断是否是当前根视图
//        UINavigationController *nav = tabBar.selectedViewController;//获取到当前视图的导航视图
//        [nav.topViewController.navigationController pushViewController:ctl animated:YES];//获取当前跟视图push到的最高视图层,然后进行push到目的页面
//    }
    // Required
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
    }
    completionHandler();  // 系统要求执行这个方法
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    //    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
    //    [JPUSHService setBadge:0];
    //    [JPUSHService resetBadge];
    // Required, iOS 7 Support
    [JPUSHService handleRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
//    HomeOneViewController *ctl = [[HomeOneViewController alloc] init];
//    MainViewController *tabBar = (MainViewController *)self.window.rootViewController;
//    if ([tabBar isKindOfClass:[UITabBarController class]]) {
//        UINavigationController *nav = tabBar.selectedViewController;
//        [nav.topViewController.navigationController pushViewController:ctl animated:YES];
//    }
//    // Required,For systems with less than or equal to iOS6
    [JPUSHService handleRemoteNotification:userInfo];
}
#pragma mark - weixinDelegate
- (BOOL)application:(UIApplication *)application handleOpenURL:(nonnull NSURL *)url{
    return [WXApi handleOpenURL:url delegate:self];
}

- (BOOL)application:(UIApplication *)application openURL:(nonnull NSURL *)url sourceApplication:(nullable NSString *)sourceApplication annotation:(nonnull id)annotation{
    return [WXApi handleOpenURL:url delegate:self];
}

- (BOOL)application:(UIApplication *)app openURL:(nonnull NSURL *)url options:(nonnull NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options{
    [WXApi handleOpenURL:url delegate:self];
    return YES;
}

-(void) onReq:(BaseReq*)req{
    if ([req isKindOfClass:[GetMessageFromWXReq class]]) {
        //微信终端向第三方程序请求提供内容的消息结构体
        //        if (self.wxDelegate
        //            && [self.wxDelegate respondsToSelector:@selector(WXApiUtilsDidRecvGetMessageReq:)]) {
        //            GetMessageFromWXReq *getMessageReq = (GetMessageFromWXReq *)req;
        //            [self.wxDelegate WXApiUtilsDidRecvGetMessageReq:getMessageReq];
        //        }
    } else if ([req isKindOfClass:[ShowMessageFromWXReq class]]) {
        //微信通知第三方程序，要求第三方程序显示的消息结构体
        //        if (self.wxDelegate
        //            && [self.wxDelegate respondsToSelector:@selector(WXApiUtilsDidRecvShowMessageReq:)]) {
        //            ShowMessageFromWXReq *showMessageReq = (ShowMessageFromWXReq *)req;
        //            [self.wxDelegate WXApiUtilsDidRecvShowMessageReq:showMessageReq];
        //        }
    } else if ([req isKindOfClass:[LaunchFromWXReq class]]) {
        //微信终端打开第三方程序携带的消息结构体
        //        if (self.wxDelegate
        //            && [self.wxDelegate respondsToSelector:@selector(WXApiUtilsDidRecvLaunchFromWXReq:)]) {
        //            LaunchFromWXReq *launchReq = (LaunchFromWXReq *)req;
        //            [self.wxDelegate WXApiUtilsDidRecvLaunchFromWXReq:launchReq];
        //        }
    }
}

//微信回调方法
- (void)onResp:(BaseResp *)resp{
    NSLog(@"resp:%d", resp.errCode);
    if ([resp isKindOfClass:[SendMessageToWXResp class]]) {
        SendMessageToWXResp *sendResp = (SendMessageToWXResp *)resp;
        NSString *str = [NSString stringWithFormat:@"%d",sendResp.errCode];
        UIAlertView *alertview = [[UIAlertView alloc] initWithTitle:@"回调信息" message:str delegate:self cancelButtonTitle:@"确认" otherButtonTitles:nil, nil];
        [alertview show];
        
    }
    if ([resp isKindOfClass:[SendAuthResp class]]) {
        SendAuthResp * rep = (SendAuthResp *)resp;
        if (rep.errCode == 0) {
            [[NSNotificationCenter defaultCenter] postNotificationName:WXAuthorizationSuccess object:@{@"code":rep.code}];
        }
    }
    if([resp isKindOfClass:[PayResp class]]){
        //支付返回结果，实际支付结果需要去微信服务器端查询
        NSString *payResoult = [NSString stringWithFormat:@"errcode:%d", resp.errCode];
        switch (resp.errCode) {
            case 0:
            {
                payResoult = @"支付结果：成功！";
                NSDictionary *dict =@{@"key":@"2"};
                NSNotification *notification =[NSNotification notificationWithName:@"支付成功success" object:nil  userInfo:dict];
                [[NSNotificationCenter defaultCenter] postNotification:notification];
            }
                break;
            case -1:
                payResoult = @"支付结果：失败！";
                break;
            case -2:
            {
                payResoult = @"用户已经退出支付！";
                
            }
                break;
            default:
                payResoult = [NSString stringWithFormat:@"支付结果：失败！retcode = %d, retstr = %@", resp.errCode,resp.errStr];
                break;
        }
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"支付结果" message:payResoult delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];
    }
}
@end
